package com.idis.userApp.controller;

import com.idis.common.util.RandomUtil;
import com.idis.service.ImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Ming on 2018/2/6.
 */
@RestController
@RequestMapping("/image")
@Api(tags = "图像接口")
public class ImageController {

    @Autowired
    ImageService imageService;

    @ApiOperation("获取图像")
    @GetMapping("/{name}.{ext}")
    public void getFile(HttpServletResponse response, @ApiParam("图像文件名")@PathVariable String name, @ApiParam("图像文件后缀名")@PathVariable String ext) throws IOException {
        String fileName=name+"."+ext;
        byte[] pic=imageService.getPicture(fileName);
        response.setHeader("Content-type","image/png");
        response.getOutputStream().write(pic);
    }

    @PostMapping("/save")
    @ApiOperation("保存图像")
    public String savaFile(@ApiParam("图像文件后缀名")@RequestParam String ext,@ApiParam("图像资源")@RequestBody MultipartFile file) throws Exception {
        Long randId= RandomUtil.randomLongId();
        String name=imageService.savePicture(file, String.valueOf(randId),ext);
        return "/image/"+name;
    }
}
